﻿using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Data;
using System.Text;

namespace funktionsPlotter
{
    public class Compiler : ICompiler
    {
        public   Func<int, int> Compilen(String p_formel)
        {
            var c = new CSharpCodeProvider();
            var cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("system.dll");

            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;

            var sb = new StringBuilder("");
            sb.Append("using System;\n");

            sb.Append("namespace CSCodeEvaler{ \n");
            sb.Append("public class CSCodeEvaler{ \n");
            sb.Append("public int EvalCode(int x){\n");
            sb.Append("return " + p_formel + "; \n");
            sb.Append("} \n");
            sb.Append("} \n");
            sb.Append("}\n");

            var cr = c.CompileAssemblyFromSource(cp, sb.ToString());
            if (cr.Errors.Count > 0)
            {
                throw new InvalidExpressionException(
                    string.Format("Error ({0}) evaluating: {1}",
                                  cr.Errors[0].ErrorText, p_formel));
            }

            var a = cr.CompiledAssembly;
            var o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
            var t = o.GetType();
            var m = t.GetMethod("EvalCode");

            return x => (int)m.Invoke(o, new object[] { x });
        }
    }
}
